/**
 * @description: 链表反转
 * @author: huen2015
 */

interface INodeList {
	value: any
	next: INodeList | null
}

function createNodeList(arr: any[]): INodeList | null {
	if (arr.length === 0) return null

	const head: INodeList = {
		value: undefined,
		next: null,
	}
	let cur: INodeList = {
		value: undefined,
		next: null,
	}

	arr.forEach((item: any, index: number) => {
		if (index === 0) {
			head.value = item
		} else if (index === 1) {
			cur.value = item
			head.next = cur
		} else {
			const node: INodeList = {
				value: item,
				next: null,
			}
			cur.next = node
			cur = node
		}
	})

	return head
}

function reverseLinkedList(nodeList: INodeList | null): INodeList | null {
	let head: INodeList | null = null
	let cur: INodeList | null = nodeList

	while (cur) {
		const next: INodeList | null = cur.next
		cur.next = head
		head = cur
		cur = next
	}
	return head
}

// 功能测试
const nodeList = createNodeList([1, 2, 3, 4, 5])
console.log('nodeList', nodeList)
console.log('reverseLinkedList', reverseLinkedList(nodeList))
